package com.cskaoyan.util;

import com.cskaoyan.exception.InfoExpiredException;
import com.cskaoyan.exception.NoInfoException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author stone
 * @date 2023/03/16 17:13
 */
@Data
public class WdTokenHolder {

    private static Map<String,InfoWithExpiredTime> map = new ConcurrentHashMap<>();

    public static Object getInfo(String key) throws NoInfoException, InfoExpiredException {
        if (key == null) {
            throw new NoInfoException();
        }
        //根据key获得value
        InfoWithExpiredTime info = map.get(key);
        if (info == null) {
            throw new NoInfoException();
        }
        // 获得过期时间和当前时间做比较
        Date expiredTime = info.getExpiredTime();
        if (new Date().after(expiredTime)) {
            map.remove(key);
            throw new InfoExpiredException();
        }
        Object validInfo = info.getInfo();
        return validInfo;
    }

    public static String genKey(Object validInfo) {
        String uuid = UUID.randomUUID().toString();
        Date now = new Date();
        // 默认的过期时间30min
        Date afterDate = getAfterDate(now, 0, 0, 0, 0, 30, 0);
        InfoWithExpiredTime info = new InfoWithExpiredTime(validInfo,afterDate);
        map.put(uuid,info);
        return uuid;
    }

    private static Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){
        if(date == null){
            date = new Date();
        }

        Calendar cal = new GregorianCalendar();

        cal.setTime(date);
        if(year != 0){
            cal.add(Calendar.YEAR, year);
        }
        if(month != 0){
            cal.add(Calendar.MONTH, month);
        }
        if(day != 0){
            cal.add(Calendar.DATE, day);
        }
        if(hour != 0){
            cal.add(Calendar.HOUR_OF_DAY, hour);
        }
        if(minute != 0){
            cal.add(Calendar.MINUTE, minute);
        }
        if(second != 0){
            cal.add(Calendar.SECOND, second);
        }
        return cal.getTime();
    }

    public static void remove() {
        map.clear();
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class InfoWithExpiredTime{
        Object info;
        Date expiredTime;
    }
}
